package com.borened.common.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Enumeration;

/**
 * restTemplate配置
 *
 * @author: cch
 * @since: 2021/12/21
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(30 * 1000);
        httpRequestFactory.setConnectTimeout(30 * 3000);
        httpRequestFactory.setReadTimeout(30 * 3000);
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        restTemplate.setInterceptors(Collections.singletonList(clientHttpRequestInterceptor()));
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestInterceptor clientHttpRequestInterceptor() {
        //传递客户端请求头参数
        return (request, body, execution) -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest currentRequest = attributes.getRequest();
            //获取请求头
            Enumeration<String> headerNames = currentRequest.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    //解决复写content-length导致请求体长度不一致报错问题。
                    if ("content-length".equalsIgnoreCase(name)) {
                        continue;
                    }
                    String values = currentRequest.getHeader(name);
                    //将请求头保存到当前请求中
                    HttpHeaders headers = request.getHeaders();
                    headers.add(name, values);
                }
            }
            //执行请求
            return execution.execute(request, body);
        };
    }
}
